package com.example.shop.config;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.shop.entity.User;
import com.example.shop.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Resource
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行 OPTIONS 请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        //------------jwt是对称加密
        System.out.println("后端已拦截==============================");
        //1.拿到token
        String token = request.getHeader("token");//从请求头拿
        if(StrUtil.isEmpty((token))){
            token = request.getParameter("token");//从参数里面拿
        }
        if(StrUtil.isBlank(token)){
            System.out.println("=======================token 为空,跳转到登录界面");
            return false;
        }
        //2.拿到用户密码
        String audience = JWT.decode(token).getAudience().get(0);
        String username = audience.split("-")[0];
        String role = audience.split("-")[1];
        User user =userService.findByUsername(username);
        if(user==null){
            System.out.println("-----------------------查到的user为空,请注册");
            return false;
        }
        //使用用户密码来验证签名
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token);
        }catch (Exception e){
            System.out.println("-----------------------token验证出错!!");
            return false;
        }
        return true;
    }
}
